<template>
  <div class="room-type-container">

    <el-card class="table-card">
      <div class="page-header">
        <h2>客房类型管理</h2>
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>添加房型
        </el-button>
      </div>
      <el-table
        v-loading="loading"
        :data="roomTypes"
        border
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="房型名称" />
        <el-table-column prop="price" label="价格">
          <template #default="{ row }">
            ¥{{ row.price }}/晚
          </template>
        </el-table-column>
        <el-table-column prop="area" label="面积">
          <template #default="{ row }">
            {{ row.area }}㎡
          </template>
        </el-table-column>
        <el-table-column prop="bedType" label="床型" />
        <el-table-column prop="capacity" label="容纳人数">
          <template #default="{ row }">
            {{ row.capacity }}人
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态">
          <template #default="{ row }">
            <el-tag :type="row.status === 'available' ? 'success' : 'danger'">
              {{ row.status === 'available' ? '可预订' : '已满房' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button-group>
              <el-button type="primary" link @click="handleEdit(row)">
                编辑
              </el-button>
              <el-button type="danger" link @click="handleDelete(row)">
                删除
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加房型' : '编辑房型'"
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="房型名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入房型名称" />
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input-number
            v-model="formData.price"
            :min="0"
            :precision="2"
            :step="100"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="面积" prop="area">
          <el-input-number
            v-model="formData.area"
            :min="0"
            :precision="0"
            :step="5"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="床型" prop="bedType">
          <el-select v-model="formData.bedType" placeholder="请选择床型" style="width: 100%">
            <el-option label="大床" value="大床" />
            <el-option label="双床" value="双床" />
            <el-option label="单人床" value="单人床" />
            <el-option label="套房" value="套房" />
          </el-select>
        </el-form-item>
        <el-form-item label="容纳人数" prop="capacity">
          <el-input-number
            v-model="formData.capacity"
            :min="1"
            :max="10"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="formData.status" placeholder="请选择状态" style="width: 100%">
            <el-option label="可预订" value="available" />
            <el-option label="已满房" value="unavailable" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<style scoped>
.room-type-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #333;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-input-number) {
  width: 100%;
}

:deep(.el-select) {
  width: 100%;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import axios from 'axios'

// 表格数据
const loading = ref(false)
const roomTypes = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref('add')
const submitting = ref(false)
const formRef = ref(null)

// 表单数据（与后端实体保持一致）
const formData = reactive({
  name: '',
  price: 0,
  area: 0,
  bedType: '',
  capacity: 1,
  status: 'available'
})

// 表单验证规则保持不变...

// 获取房型列表（对接分页接口）
const fetchRoomTypes = async () => {
  loading.value = true
  try {
    const response = await axios.get('/api/room-types', {
      params: {
        page: currentPage.value - 1, // Spring Data 分页从 0 开始
        size: pageSize.value
      }
    })
    roomTypes.value = response.data.content
    total.value = response.data.totalElements
  } catch (error) {
    ElMessage.error('获取房型列表失败: ' + error.response?.data?.message)
  } finally {
    loading.value = false
  }
}

// 添加房型（对接创建接口）
const handleAdd = () => {
  dialogType.value = 'add'
  dialogVisible.value = true
  resetForm()
}

// 编辑房型（对接更新接口）
const handleEdit = (row) => {
  dialogType.value = 'edit'
  dialogVisible.value = true
  Object.assign(formData, {
    ...row,
    // 转换类型（如果后端需要特定类型）
    price: Number(row.price),
    area: Number(row.area),
    capacity: Number(row.capacity)
  })
}

// 删除房型（对接删除接口）
const handleDelete = (row) => {
  ElMessageBox.confirm(
      '确定要删除该房型吗？',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(async () => {
    try {
      await axios.delete(`/api/room-types/${row.id}`)
      ElMessage.success('删除成功')
      fetchRoomTypes()
    } catch (error) {
      ElMessage.error('删除失败: ' + error.response?.data?.message)
    }
  })
}

// 提交表单（统一处理创建/更新）
const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        const apiCall = dialogType.value === 'add'
            ? axios.post('/api/room-types', formData)
            : axios.put(`/api/room-types/${formData.id}`, formData)

        const response = await apiCall
        ElMessage.success(dialogType.value === 'add' ? '添加成功' : '编辑成功')
        dialogVisible.value = false
        fetchRoomTypes()
      } catch (error) {
        const errorMsg = error.response?.data?.message || '操作失败'
        ElMessage.error(`${dialogType.value === 'add' ? '添加' : '编辑'}失败: ${errorMsg}`)
      } finally {
        submitting.value = false
      }
    }
  })
}

// 重置表单数据
const resetForm = () => {
  Object.assign(formData, {
    name: '',
    price: 0,
    area: 0,
    bedType: '',
    capacity: 1,
    status: 'available'
  })
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1 // 切换每页大小重置到第一页
  fetchRoomTypes()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchRoomTypes()
}

// 初始化
onMounted(() => {
  fetchRoomTypes()
})
</script>